#include "qtcpfiletransfer.h"
#include "ui_qtcpfiletransfer.h"
#define LISTEN_PORT 8000
QTcpFileTransfer::QTcpFileTransfer(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::QTcpFileTransfer)
{
    ui->setupUi(this);

    qTcpServer = new QTcpServer(this);
    ui->SelectFileButton->setEnabled(false);
    ui->StartTransferButton->setEnabled(false);
    ui->textEdit->setReadOnly(true);
    bool isListenOk = qTcpServer->listen(QHostAddress::Any,LISTEN_PORT);
    if (isListenOk) {
        this->setWindowTitle(QString("服务器监听端口:%1").arg(LISTEN_PORT));
        connect(qTcpServer,&QTcpServer::newConnection,
                [=](){

            qTcpSocket = qTcpServer->nextPendingConnection();

            QString ip = qTcpSocket->peerAddress().toString();
            quint16 port = qTcpSocket->peerPort();

            QString connectText = QString("新建客户端连接:%1:%2")
                    .arg(ip)
                    .arg(port);

            ui->SelectFileButton->setEnabled(true);
            ui->StartTransferButton->setEnabled(true);

            ui->textEdit->append(connectText);
        });
    }else {
        ui->textEdit->append(QString("绑定端口:%1失败!").arg(LISTEN_PORT));
    }
}

QTcpFileTransfer::~QTcpFileTransfer()
{
    delete ui;
}

void QTcpFileTransfer::on_SelectFileButton_clicked()
{
    QString readFileName = QFileDialog::getOpenFileName(
                this
                ,tr("Open Text")
                ,"../");
    qDebug()<<readFileName;
    if (!readFileName.isEmpty()) {
        ui->lineEdit->setText(readFileName);
    }
}

void QTcpFileTransfer::on_StartTransferButton_clicked()
{

    QString readFileName = ui->lineEdit->text();

    QFile qFile(readFileName);
    bool isOpenOk = qFile.open(QIODevice::ReadOnly);
    if (isOpenOk) {
        const int readLength=1024;
        QFileInfo qFileInfo(readFileName);
        QString packageHead = QString("HEAD###%1###%2###%3")
                .arg(qFileInfo.fileName()).arg(qFileInfo.size())
                .arg("HEADEND");

        ui->textEdit->append(QString("开始发送包头:%1").arg(packageHead));
        QByteArray sendHead;
        sendHead.insert(0,packageHead.toUtf8());
        sendHead.resize(300);
        qint64 writeHeadStatus = qTcpSocket->write(sendHead);
        if (writeHeadStatus>0) {
            ui->textEdit->append("包头发送成功!开始发送数据...");
            qint64 readSize;
            qint64 sendSize;
            char buf[readLength]={0};
            do{
                readSize= qFile.read(buf,readLength);
                sendSize= qTcpSocket->write(buf,readSize);
                //文件读取内容不为空,并且发送成功
            } while (readSize>0 && sendSize>0);
            qFile.close();
            ui->textEdit->append("服务端数据发送完成!");
        }
    }
}
